<template>
  <view class="add-post-container">
    <!-- 顶部导航 -->
    <view class="top-nav">
      <view class="page-title">发布帖子</view>
    </view>

    <!-- 内容输入区 -->
    <scroll-view class="content-scroll" scroll-y>
      <view class="content-area">
        <!-- 标题输入 -->
        <view class="input-group">
          <input 
            type="text" 
            v-model="postTitle" 
            placeholder="请输入标题" 
            class="title-input"
          />
        </view>

        <!-- 内容输入 -->
        <view class="input-group">
          <textarea 
            v-model="postContent" 
            placeholder="分享你的想法..." 
            class="content-input"
            auto-height
          ></textarea>
        </view>

        <!-- 图片上传区 -->
        <view class="section-title">添加图片</view>
        <view class="image-upload-area">
          <!-- 已选图片 -->
          <view class="image-item" v-for="(img, index) in selectedImages" :key="index">
            <image :src="img" mode="aspectFill" class="uploaded-image"></image>
            <view class="delete-btn" @tap.stop="deleteImage(index)">
              <text class="iconfont">×</text>
            </view>
          </view>

          <!-- 添加图片按钮 -->
          <view class="add-image-btn" @tap="chooseImage" v-if="selectedImages.length < 9">
            <text class="iconfont">+</text>
          </view>
          <view class="image-count-hint" v-if="selectedImages.length > 0">
            {{ selectedImages.length }}/9 张图片
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部发布按钮 -->
    <view class="bottom-bar">
      <view class="publish-btn" @tap="publishPost" :class="{ disabled: isPublishDisabled }">
        {{ isPublishing ? '发布中...' : '发布帖子' }}
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import userManager from '@/common/utils/user.js';
import { addPost,uploadImage } from '@/api/post.js';
// 帖子数据
const postTitle = ref('')
const postContent = ref('')
const selectedImages = ref([])
const isPublishing = ref(false) // 发布状态，防止重复点击

// 计算是否可以发布 - 修改这里的判断条件
const isPublishDisabled = computed(() => {
  // 标题或内容为空时，或者正在发布中，禁用发布按钮
  return !postTitle.value.trim() || !postContent.value.trim() || isPublishing.value
})

// 选择图片
const chooseImage = () => {
  const maxCount = 9 - selectedImages.value.length
  if (maxCount <= 0) return

  uni.chooseImage({
    count: maxCount,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      selectedImages.value = [...selectedImages.value, ...res.tempFilePaths]
    }
  })
}

// 删除图片
const deleteImage = (index) => {
  selectedImages.value.splice(index, 1)
}

// 发布帖子
const publishPost = async() => {
  // 防止重复点击
  if (isPublishDisabled.value || isPublishing.value) return
  
  // 检查登录状态
  if (!userManager.checkLogin()) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    setTimeout(() => {
      uni.switchTab({
        url: '/pages/mine/mine'
      })
    }, 1000)
    return
  }
  
  // 设置发布状态
  isPublishing.value = true
  uni.showLoading({ title: '发布中...', mask: true })
  
  const ossImageUrls = [] // 每次发布时重新初始化数组
  
  try {
    // 1. 上传图片到OSS
    if (selectedImages.value.length > 0) {
      for (let i = 0; i < selectedImages.value.length; i++) {
        const tempPath = selectedImages.value[i]
        try {
          const ossUrl = await uploadImage(tempPath)
          if (ossUrl) {
            ossImageUrls.push(ossUrl) // 收集OSS URL
          } else {
            throw new Error('图片上传失败')
          }
        } catch (uploadError) {
          console.error(`第${i + 1}张图片上传失败:`, uploadError)
          throw new Error(`第${i + 1}张图片上传失败，请重试`)
        }
      }
    }
    
    // 2. 构建帖子数据对象
    const userInfo = userManager.getUserInfo()
    const postData = {
      userId: userInfo?.userId || '', 
      title: postTitle.value.trim(),
      content: postContent.value.trim(),
      images: ossImageUrls,
    }
    
    console.log('发布的帖子数据:', postData)
    console.log('格式化的帖子数据:', JSON.stringify(postData, null, 2))
    
    // 3. 调用发布接口
    const result = await addPost(postData)
    
    // 4. 处理发布结果
    // 检查返回结果：如果 result 存在且 code 为 200，则认为成功
    // 注意：即使 data 为 null，只要 code 为 200 也表示成功（后端可能返回 success() 不带数据）
    if (result && result.code === 200) {
      // 发布成功
      uni.hideLoading()
      uni.showToast({
        title: '发布成功',
        icon: 'success',
        duration: 2000
      })
      
      // 发布成功后返回首页
      // 注意：保持 isPublishing 为 true，直到页面跳转，防止用户重复点击
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/index/index'
        })
        // 页面跳转后，组件会被销毁，状态会自动重置
        // 但为了保险起见，在跳转前重置状态（虽然可能不会执行到）
        isPublishing.value = false
      }, 2000)
      // 成功时不在这里重置状态，保持按钮禁用直到跳转
      return
    } else {
      // 发布失败（接口返回null、undefined，或code不为200）
      const errorMsg = result?.message || '发布失败，请重试'
      throw new Error(errorMsg)
    }
  } catch (error) {
    // 处理错误
    console.error('发布帖子失败:', error)
    uni.hideLoading()
    uni.showToast({
      title: error.message || '发布失败，请检查网络后重试',
      icon: 'none',
      duration: 3000
    })
    // 失败时重置发布状态，允许用户重试
    isPublishing.value = false
  }
}
</script>

<style scoped>
.add-post-container {
  min-height: 100vh;
  background-color: #F8F9FA;
  display: flex;
  flex-direction: column;
}

/* 顶部导航 */
.top-nav {
  padding: 24rpx 32rpx;
  background-color: #FFFFFF;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-title {
  font-size: 34rpx;
  font-weight: 600;
  color: #1A1A1A;
}

/* 滚动内容区 */
.content-scroll {
  flex: 1;
  overflow-y: auto;
}

/* 内容区域 */
.content-area {
  padding: 32rpx;
}

/* 输入组样式 */
.input-group {
  background-color: #FFFFFF;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.02);
  transition: box-shadow 0.2s;
}

.input-group:focus-within {
  box-shadow: 0 4rpx 12rpx rgba(137, 207, 240, 0.15);
}

/* 标题输入 */
.title-input {
  width: 100%;
  font-size: 34rpx;
  line-height: 1.4;
  color: #1A1A1A;
}

.title-input::placeholder {
  color: #C9CDD4;
  font-weight: 400;
}

/* 内容输入 */
.content-input {
  width: 100%;
  font-size: 28rpx;
  line-height: 1.6;
  color: #333333;
  min-height: 220rpx;
}

.content-input::placeholder {
  color: #C9CDD4;
}

/* 分区标题 */
.section-title {
  font-size: 28rpx;
  color: #6B7280;
  margin: 32rpx 0 16rpx;
  display: flex;
  align-items: center;
}

.section-title::before {
  content: "";
  display: inline-block;
  width: 8rpx;
  height: 28rpx;
  background-color: #89CFF0;
  border-radius: 4rpx;
  margin-right: 12rpx;
}

/* 图片上传区 */
.image-upload-area {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-bottom: 220rpx; /* 预留底部按钮空间 */
}

.image-item {
  width: 168rpx;
  height: 168rpx;
  position: relative;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  transition: transform 0.2s;
}

.image-item:hover {
  transform: scale(1.02);
}

.uploaded-image {
  width: 100%;
  height: 100%;
}

.delete-btn {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(255, 68, 68, 0.9);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
  transition: background-color 0.2s;
}

.delete-btn:hover {
  background-color: rgba(255, 68, 68, 1);
}

.add-image-btn {
  width: 168rpx;
  height: 168rpx;
  border: 2rpx dashed #C9CDD4;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 48rpx;
  color: #94A3B8;
  background-color: #F8FAFC;
  transition: all 0.2s;
}

.add-image-btn:hover {
  border-color: #89CFF0;
  color: #89CFF0;
  background-color: #F0F9FF;
}

.image-count-hint {
  width: 100%;
  margin-top: 16rpx;
  font-size: 24rpx;
  color: #94A3B8;
  padding-left: 4rpx;
}

/* 底部发布按钮 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 24rpx 32rpx;
  background-color: #FFFFFF;
  border-top: 1px solid #F1F5F9;
  box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.03);
}

.publish-btn {
  width: 100%;
  height: 96rpx;
  background-color: #89CFF0;
  color: #FFFFFF;
  font-size: 32rpx;
  border-radius: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 500;
  transition: all 0.2s;
  letter-spacing: 2rpx;
}

.publish-btn:not(.disabled) {
  box-shadow: 0 4rpx 16rpx rgba(137, 207, 240, 0.3);
}

.publish-btn:not(.disabled):active {
  background-color: #6BBBF7;
  transform: scale(0.99);
  box-shadow: 0 2rpx 8rpx rgba(137, 207, 240, 0.2);
}

.publish-btn.disabled {
  background-color: #D1D5DB;
  color: #9CA3AF;
  cursor: not-allowed;
}

/* 适配安全区域 */
::v-deep .content-scroll {
  padding-bottom: env(safe-area-inset-bottom);
}

::v-deep .bottom-bar {
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
}
</style>